<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div>
       
        <!-- 搜索 -->
        <el-input v-model="query.value" clearable placeholder="输入搜索内容" style="width: 200px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <el-select v-model="query.type" clearable placeholder="类型" class="filter-item" style="width: 130px">
          <el-option v-for="item in queryTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
        <el-select v-model="statusType" clearable placeholder="状态" class="filter-item" style="width: 130px">
        <el-option
          v-for="item in statusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
	  <el-select v-model="query.businessId" clearable placeholder="商户列表" class="filter-item" filterable style="width: 200px" @change="crud.toQuery">
	    <el-option v-for="item in businessNameList" 
	      :value="item.id"
	      :key="item.id"
	      :label="item.businessName">
	    </el-option>
	  </el-select>
        <rrOperation :crud="crud" />
        
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <!-- <crudOperation :permission="permission" /> -->
      <el-button
          v-permission="['admin','syUserService:add']"
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-plus"
          @click="crud.toAdd"
        >新增</el-button>
      <!--表单组件-->
      <el-drawer
        :title="removeTitle"
        size="35%"
        :visible.sync="drawer"
        :direction="direction"
        :before-close="handleClose">
        <el-divider content-position="left">要迁移到客服对象</el-divider>
        <el-form :model="ruleForm" :rules="rulesForm" ref="ruleForm" label-width="120px" class="demo-ruleForm">
          <el-form-item label="迁移到客服" prop="moveService">
            <el-select v-model="ruleForm.moveService" clearable filterable placeholder="请选择要迁移到客服对象" style="width: 90%;">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-button type="primary" :loading="moveLoading" @click="submitForm('ruleForm')">立即迁移</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form>
        <el-divider content-position="left">迁移穿梭框</el-divider>
          <el-transfer 
            filterable
            :titles="titlesMsg"
            :filter-method="filterMethod"
            filter-placeholder="请输入客户手机号"
            v-model="moveValue"
            :data="data">
          </el-transfer>
      </el-drawer>
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="900px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-row>
            <el-col class="query-class">
              <el-form-item label="选择用户" prop="userName">
                <el-input v-model="form.userName" placeholder="请输入会员账号" style="width:370px;" clearable :disabled="nameDisabled"/>
              </el-form-item>
              <el-form-item style="margin-left: -75px;!important;">
                <el-input v-model="form.uid" v-show="false"/>
                <el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="toQuery" :disabled="nameDisabled">搜索</el-button>
              </el-form-item>
              <div class="font-class">{{msg}}</div>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="客服昵称" prop="nickname">
                <el-input v-model="form.nickname" :disabled="isDisabledInput"/>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="手机号码" prop="phone">
                <el-input v-model="form.phone" :disabled="isDisabledInput"/>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="form.status" :disabled="isDisabledInput">
                  <el-radio label="1">正常</el-radio>
                  <el-radio label="0">禁止</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="微信号" prop="wechatNumber">
                <el-input v-model="form.wechatNumber" :disabled="isDisabledInput"/>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="工作经验">
                <el-input v-model="form.workExperience" type="number" :disabled="isDisabledInput"/>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="服务星级">
                <el-input v-model="form.serviceStar" type="number" :disabled="isDisabledInput"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="客服类型" prop="servicType">
                <el-select v-model="form.servicType" placeholder="请选择活客服类型">
                  <el-option label="公共客服" value="0"></el-option>
                  <el-option label="BD" value="1"></el-option>
                  <el-option label="BDM" value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="14" v-if="form.servicType==1">
              <el-form-item label="上级BDM">
                <el-select style="width:100%;" v-model="form.parentId" filterable placeholder="请选择上级BDM">
                  <el-option v-for="item in bdmList" :key="item.uid" :label="item.nickname+'['+item.phone+']'" :value="item.uid"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="14" v-if="form.servicType==2">
              <el-form-item label="负责区域">
                <el-select style="width:100%;" v-model="regionIdsValue" multiple filterable allow-create default-first-option placeholder="请选择负责区域">
                  <el-option v-for="item in regionList" :key="item.id" :label="item.mergerName+'['+item.templateDesc+']'" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="用户头像">
              <MaterialList
                      v-model="avatarArr"
                      style="width: 915px;"
                      type="image"
                      :num="1"
                      :width="150"
                      :height="150"
                      :disabled="isDisabledInput"
              />
          </el-form-item>
          
          <el-form-item label="工作时间" prop="workingHours">
            <el-input v-model="form.workingHours" :disabled="isDisabledInput"/>
          </el-form-item>
          
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="submitCUInfo">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" 
      :data="crud.data" size="small" style="width: 100%;" 
      row-key="uid" default-expand-all
     :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" v-if="false"/>
        <el-table-column v-if="columns.visible('userName')" prop="userName" width="130" label="用户号" show-overflow-tooltip/>
        <el-table-column v-if="columns.visible('status')" prop="status" label="客服类型" width="80" >
          <template slot-scope="scope">
            <div>
              <el-tag v-if="scope.row.servicType == 2" :type="''">BDM</el-tag>
              <el-tag v-else-if="scope.row.servicType == 1" :type="''">BD</el-tag>
              <el-tag v-else :type=" 'info' ">公共客服</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="columns.visible('nickname')" prop="nickname" label="客服昵称" show-overflow-tooltip/>
          <el-table-column v-if="columns.visible('avatar')" prop="avatar" label="用户头像" width="80">
            <template slot-scope="scope">
              <a :href="scope.row.avatar" style="color: #42b983" target="_blank">
                <img :src="scope.row.avatar" alt="点击打开" class="table-img" />
              </a>
            </template>
          </el-table-column>
        <el-table-column v-if="columns.visible('phone')" prop="phone" label="手机号码" width="100"/>
        <el-table-column v-if="columns.visible('wechatNumber')" prop="wechatNumber" label="微信号" show-overflow-tooltip/>
        <el-table-column v-if="columns.visible('workExperience')" prop="workExperience" label="工作经验" width="80"/>
        <el-table-column v-if="columns.visible('serviceStar')" prop="serviceStar" label="服务星级" width="80"/>
        <el-table-column v-if="columns.visible('businessName')" prop="businessName" label="所属招商" width="80" show-overflow-tooltip/>
        <el-table-column v-if="columns.visible('workingHours')" prop="workingHours" label="工作时间" show-overflow-tooltip/>
        <el-table-column v-if="columns.visible('userCount')" prop="userCount" label="用户总数" />
        <el-table-column v-if="columns.visible('status')" prop="status" label="状态" width="60" >
          <template slot-scope="scope">
            <div>
              <el-tag v-if="scope.row.status == 1" :type="''">正常</el-tag>
              <el-tag v-else :type=" 'info' ">禁用</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column v-permission="['admin','syUserService:edit','syUserService:del','syUserService:move']" label="操作" width="200px" align="center">
          <template slot-scope="scope">
            <div style="display: flex;">
              <udOperation
              :data="scope.row"
              :permission="permission"
            />
            &nbsp;
            <el-button
            v-permission="['admin','syUserService','move']"
            size="mini"
            type="danger"
            @click="moveSyUser(scope.row)"
          >迁移客户</el-button>
            </div>
            
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudSyUserService from '@/api/syUserService'
import { getUserByName, getUserByUidList, moveJsonDataUpdate , getRegionAndBdmList} from '@/api/syUserService'
import CRUD, { presenter, header, form, crud } from '@crud/cruid'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UID.operation'
import pagination from '@crud/Pagination'
import { Message } from 'element-ui'
import MaterialList from "@/components/material";
import { getBusinessNameList } from '@/api/syBusinessName'

// crud交由presenter持有
const defaultCrud = CRUD({ title: '客服', url: 'api/syUserService', sort: 'uid,desc', crudMethod: { ...crudSyUserService }})
const defaultForm = { uid: null,userName:null, nickname: null, avatar: null, phone: null, wechatNumber: null,
   workExperience: 3, serviceStar: 5, workingHours: '早上 09:00 - 晚上 21:00', status: '1',regionIds:'',parentId:null,
   servicType:'0', createTime: null, updateTime: null }
export default {
  name: 'SyUserService',
  components: { pagination, crudOperation, rrOperation, udOperation ,MaterialList},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  dicts: ['is_enable'],
  data() {
    const generateData = _ => {
      const data = [];
      const cities = [];
      const pinyin = [];
      cities.forEach((city, index) => {
        data.push({
          label: city,
          key: index,
          pinyin: pinyin[index]
        });
      });
      return data;
    };
    return {
      regionIdsValue:[],
      regionList:[],
      bdmList:[],
      statusType: '',
      statusOptions: [
        { value: '1', label: '正常' },
        { value: '0', label: '禁止' }
      ],
      titlesMsg:['被迁移客户列表', '已迁移客户列表'],
      ruleForm: {
        moveService: ''
      },
      rulesForm: {
        moveService: [
          { required: true, message: '请选择要迁移到客服对象', trigger: 'change' }
        ]
      }, 
      oldUid:'',
      moveLoading:false,
      options: [],
      data: generateData(),
      moveValue: [],
      filterMethod(query, item) {
        return item.pinyin.indexOf(query) > -1;
      },
      removeTitle:'',
      drawer: false,
      direction: 'rtl',
      msg:'',
      isDisabledInput:true,
      nameDisabled:false,
      avatarArr:[],
      permission: {
        add: ['admin', 'syUserService:add'],
        edit: ['admin', 'syUserService:edit'],
        del: ['admin', 'syUserService:del'],
        move: ['admin', 'syUserService:move']
      },
      rules: {
        nickname: [
          { required: true, message: '客服昵称不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' }
        ],
        wechatNumber: [
          { required: true, message: '微信号不能为空', trigger: 'blur' }
        ],
        workingHours: [
          { required: true, message: '工作时间不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '1为正常，0为禁止不能为空', trigger: 'blur' }
        ],
        servicType: [
          { required: true, message: '客服类型不能为空', trigger: 'blur' }
        ],
        
      },
      queryTypeOptions: [
        { key: 'nickname', display_name: '客服昵称' },
        { key: 'phone', display_name: '手机号码' },
        { key: 'wechatNumber', display_name: '微信号' },
        { key: 'status', display_name: '1为正常，0为禁止' }
      ],
	  businessNameList: [],//商户列表
    }
  },
  watch: {
    "avatarArr":function(val) {
      if (val) {
        this.form.avatar = val.join(",");
      }
    }
  },
  created() {
    let that = this;
    setTimeout(function() {
      that.getRegionAndBdmListInit();
	   that.getBusinessListInit();
    }, 500);
  },
  methods: {
    getRegionAndBdmListInit(){
      getRegionAndBdmList().then(res => {
        this.bdmList = res.bdmList;
        this.regionList = res.regionList;
      })
    },
	getBusinessListInit(){
	  getBusinessNameList().then(res => {
	    this.businessNameList = res;
	  })
	},
    getLstInteger(str){
      let lStrTemp = [];
      str.split(',').map(u=>{lStrTemp.push(parseInt(u))});
      return lStrTemp;
    },
    submitCUInfo(){
      this.form.regionIds = JSON.stringify(this.regionIdsValue);
      this.crud.submitCU();
      this.getRegionAndBdmListInit();
    },
    submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if(this.moveValue.length > 0){
                this.moveLoading = true
                let oldUid = this.oldUid;
                let moveServiceUid = this.ruleForm.moveService;
                let moveValue = this.moveValue;
                moveJsonDataUpdate({oldUid:oldUid,moveServiceUid:moveServiceUid,moveValue:moveValue}).then(res => {
                  this.oldUid='';
                  this.ruleForm.moveService ='';
                  this.moveValue = [];
                  this.data=[];
                  this.options = [];
                  this.moveLoading = false
                  Message({ message: '迁移成功', type: 'success' });
                  this.crud.toQuery();
                  this.drawer = false;
                }).catch(err => {
                  this.oldUid='';
                  this.ruleForm.moveService ='';
                  this.moveValue = [];
                  this.data=[];
                  this.options = [];
                  this.moveLoading = false
                })
            }else{
              this.$message({
                message: '请选择被迁移的账号！',
                type: 'warning'
              });
              return false;
            }
           
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
    moveSyUser(scope) {
      this.removeTitle='该'+scope.userName+'['+scope.nickname+']客服下所有的客户迁移操作?';
      this.getUserServiceList(scope.uid);
      
    },
    handleClose(done) {
      this.oldUid='';
      this.ruleForm.moveService ='';
      this.moveValue = [];
      this.data=[];
      this.options = [];
      this.oldUid = '';
      done();
    },
    getUserServiceList(uid){
      getUserByUidList({uid:uid}).then(res => {
        this.data =res.selectList;
        this.options = res.syServiceList;
        this.oldUid = uid;
        this.drawer = true;
      })
    },
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      const query = this.query
      if (query.type && query.value) {
        this.crud.params[query.type] = query.value
      }else{
        delete this.crud.params.nickname
        delete this.crud.params.phone
        delete this.crud.params.wechatNumber
        delete this.crud.params.status
		delete this.crud.params.businessId
        this.statusType ='';
      }
      if(this.statusType){
        this.crud.params.status = this.statusType;
      }else{
        delete this.crud.params.status
      }
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.form.status = form.status.toString();
      this.form.servicType = form.servicType.toString();
      if (form.parentId && form.uid) {
        this.form.parentId = form.parentId;
      }else{
        this.form.parentId = '';
      }
      if (form.regionIds && form.uid) {
        this.regionIdsValue= this.getLstInteger(form.regionIds);
      }else{
        this.regionIdsValue= [];
      }
      this.msg = '';
      if (form.avatar && form.uid) {
        this.avatarArr = form.avatar.split(",");
        this.isDisabledInput = false;
        this.nameDisabled = true;
      }else{    
        this.isDisabledInput = true;
        this.nameDisabled = false;
        this.avatarArr=[]
      }
    },
    toQuery(){
      let userName = this.form.userName;
      if(userName){
        getUserByName({userName:userName}).then(res => {
          if(res.code =='0'){
            this.isDisabledInput = false;
            this.nameDisabled = true;
            this.form.phone = res.yxUser.phone;
            this.form.uid = res.yxUser.uid;
            this.form.nickname = res.yxUser.nickname;
            if(res.yxUser.avatar){
              this.avatarArr = res.yxUser.avatar.split(",");
            }
            this.msg = '';
          }else if(res.code =='2'){//说明已存在
              this.msg = '该会员账号已存在！请检查…';
              this.isDisabledInput = true;
              this.nameDisabled = false;
          }else{
              this.msg = '该会员账号不存在！请检查…';
              this.isDisabledInput = true;
              this.nameDisabled = false;
          }
          
        })
      }else{
        this.msg = '';
        this.isDisabledInput = true;
        this.nameDisabled = false;
        this.$message({
          message: '请输入搜索会员账号！',
          type: 'warning'
        });
      }
      
    }
  }
}



</script>

<style scoped>
  .el-drawer__header{
    font-weight: bold !important;
    font-size: 14px !important;
  }
  .table-img {
    display: inline-block;
    text-align: center;
    background: #ccc;
    color: #fff;
    white-space: nowrap;
    position: relative;
    overflow: hidden;
    vertical-align: middle;
    width: 32px;
    height: 32px;
    line-height: 32px;
  }
  .query-class{
    display: flex;
  }
  .font-class{
    color: red;
    margin-top: 5px;
    font-weight: 500;
    margin-left: 5px;
  }
  

</style>
